package com.sws.worktive;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.database.Cursor;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.crashlytics.android.Crashlytics;
import com.sws.worktive.model.Jobs;
import com.sws.worktive.task.ServerDownload;
import com.sws.worktive.task.ServerResponse;
import com.sws.worktive.util.CameraPreview;
import com.sws.worktive.util.ConnectionDector;
import com.sws.worktive.util.Constant;
import com.sws.worktive.util.WT_Prefrences;

//LOCALIZATION
/*
 *  http://stackoverflow.com/questions/2264874/changing-locale-within-the-app-itself
 *  
 *  http://www.icanlocalize.com/site/tutorials/android-application-localization-tutorial/
 */

public class DrawerFragment extends FragmentActivity implements OnClickListener ,DrawerListener {

	DrawerLayout drawerLayout;
	LinearLayout mLeftDrawerRoot, mRightDrawerRoot;
	String picturePath;
	LinearLayout rl_signIn,rl_signUp;
	RelativeLayout  rl_Profile, rl_signOut;
	TextView txtAvailablePost;
	EditText edt_zipcode;
	ArrayAdapter<com.sws.worktive.model.Category> adapterJobTitle;
	Spinner spn_MilesRadius, spn_JobTitle, spn_JobType, spn_Language;
	WT_Prefrences prefrences;

	int val_MilesRadius = 5, val_JobType, val_Language;

	ArrayList<Jobs> arrJobs = new ArrayList<Jobs>();
	List<com.sws.worktive.model.Category> arrCategories = new ArrayList<com.sws.worktive.model.Category>();
	public static final String TAG = "DrawerScreen";

	ProgressDialog mProgressDialog;

	public String getCameraImagePath() {
		return picturePath;
	}

	public void setCameraImagePath(String cameraImagePath) {
		this.picturePath = cameraImagePath;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Crashlytics.start(this);
		setContentView(R.layout.drawer_screen);
		getAppKeyHash();

		drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		drawerLayout.setDrawerListener(this);
		mLeftDrawerRoot = (LinearLayout) findViewById(R.id.left_drawer_root);
		mRightDrawerRoot = (LinearLayout) findViewById(R.id.right_drawer_root);

		prefrences = new WT_Prefrences(DrawerFragment.this);
		
		// Feilds of Left Drawer
		rl_signIn = (LinearLayout) mLeftDrawerRoot
				.findViewById(R.id.signin_feild);
		rl_signUp = (LinearLayout) mLeftDrawerRoot
				.findViewById(R.id.signup_feild);
		rl_Profile = (RelativeLayout) mLeftDrawerRoot
				.findViewById(R.id.profile_feild);
		rl_signOut = (RelativeLayout) mLeftDrawerRoot
				.findViewById(R.id.signout_feild);
		
		//TODO:delete the next line of code when profile function is on the plan to implement
		hideProfileField();

		rl_signIn.setOnClickListener(this);
		rl_signUp.setOnClickListener(this);
		rl_Profile.setOnClickListener(this);
		rl_signOut.setOnClickListener(this);

		if(!prefrences.getToken().equals("") && prefrences.getPhonenumber()!=0){
			hideSignInField();
			hideSignUpField();
			showSignOutField();
		}else {
			hideSignOutField();
		}

		// Feilds of Right Drawer

		edt_zipcode = (EditText) findViewById(R.id.edt_zipcode);

		spn_MilesRadius = (Spinner) findViewById(R.id.spn_mile_radius);
		ArrayAdapter<CharSequence> adapterRadius = ArrayAdapter
				.createFromResource(DrawerFragment.this,
						R.array.array_miles_radius, R.layout.spinner_item);

		adapterRadius.setDropDownViewResource(R.layout.spinner_item);
		spn_MilesRadius.setAdapter(adapterRadius);

		spn_JobTitle = (Spinner) findViewById(R.id.spn_job_title);
		adapterJobTitle = new ArrayAdapter<com.sws.worktive.model.Category>(
				DrawerFragment.this, R.layout.spinner_item, arrCategories);
		
		adapterRadius.setDropDownViewResource(R.layout.spinner_item);
		spn_JobTitle.setAdapter(adapterJobTitle);

		spn_JobType = (Spinner) findViewById(R.id.spn_job_type);
		ArrayAdapter<CharSequence> adapterJobType = ArrayAdapter
				.createFromResource(DrawerFragment.this, R.array.array_job_type,
						R.layout.spinner_item);

		adapterRadius.setDropDownViewResource(R.layout.spinner_item);
		spn_JobType.setAdapter(adapterJobType);

		spn_Language = (Spinner) findViewById(R.id.spn_language);
		ArrayAdapter<CharSequence> adapterLanguage = ArrayAdapter
				.createFromResource(DrawerFragment.this, R.array.array_languages,
						R.layout.spinner_item);

		adapterRadius.setDropDownViewResource(R.layout.spinner_item);
		spn_Language.setAdapter(adapterLanguage);

		if (savedInstanceState == null) {
			addFragment(0);
		}
	}

	private void getAppKeyHash() {
		try {
			PackageInfo info = getPackageManager().getPackageInfo(
					getPackageName(), PackageManager.GET_SIGNATURES);
			for (Signature signature : info.signatures) {
				MessageDigest md;

				md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				String something = new String(Base64.encode(md.digest(), 0));
				Log.d("Hash key", something);
			}
		} catch (NameNotFoundException e1) {
			Log.e("name not found", e1.toString());
		}

		catch (NoSuchAlgorithmException e) {
			Log.e("no such an algorithm", e.toString());
		} catch (Exception e) {
			Log.e("exception", e.toString());
		}

	}

	// Adding Fragment
	public void addFragment(int position) {
		Fragment fragment = null;
		FragmentManager fragmentManager = getSupportFragmentManager();
		String tag = "";
		switch (position) {
			case 0:
				
				if(!prefrences.getToken().equals("") && prefrences.getPhonenumber()!=0){
					hideSignInField();
					hideSignUpField();
					showSignOutField();
				}
				
				tag = Constant.HOME_FRAGMENT;
				fragment = fragmentManager.findFragmentByTag(tag);
				if (fragment == null) {
					fragment = new HomeFragment();
				}
				break;
	
			case 1:
				tag = Constant.SIGNIN_FRAGMENT;
				fragment = SigInFragment.newInstance(fragmentManager, tag);
				break;
	
			case 2:
				tag = Constant.SIGNUP_FRAGMENT;
				fragment = SignUpFragment.newInstance(fragmentManager, tag);
	
				break;
			case 3:
				tag = Constant.PROFILE_FRAGMENT;			
				fragment = ProfileFragment.newInstance(fragmentManager, tag);
				break;
	
			case 4:
				tag = Constant.PHOTOPOSTING_FRAGMENT;			
				fragment = PhotoPostingFragment.newInstance(fragmentManager, tag, picturePath, isCameraPreview);

				break;
				
			case 5:
				tag = Constant.DESCRIPTION_FRAGMENT;
					fragment = new DescriptionPostFragment();
				break;
			default:
				break;
		}
		if (fragment != null) {
			fragmentManager.popBackStack();
			if (position != 0) {
				if (fragment != null) {
					fragmentManager.beginTransaction()
					.replace(R.id.content_frame, fragment, tag)
					.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
					.addToBackStack(null).commit();
				}
			} else {
				fragmentManager.beginTransaction()
						.replace(R.id.content_frame, fragment, tag).commit();
			}
		}

		drawerLayout.closeDrawer(mLeftDrawerRoot);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.signin_feild:
			addFragment(1);
			break;
		case R.id.signup_feild:
			addFragment(2);
			break;
		case R.id.profile_feild:
			addFragment(3);
			break;
		case R.id.signout_feild:
			prefrences.setToken("");
			prefrences.setPhonenumber(0);
			showSignInField();
			showSignUpField();
			hideSignOutField();
			
			break;
		case R.id.button_Save:

			break;

		case R.id.button_Cancel:

			break;

		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);

		if (arg1 != -1)
			return;

		switch (arg0) {
		case Constant.CAMERA_REQUEST:
			if (arg2 != null) {
				Uri selectedImage = arg2.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);

				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				picturePath = cursor.getString(columnIndex);
				cursor.close();
				addFragment(4);
			} else {
				Log.v("ImagePath : ", picturePath);
				addFragment(4);

			}
			break;

		case Constant.GALLERY_REQUEST:

			if (arg2 != null) {
				Uri selectedImage = arg2.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);

				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				picturePath = cursor.getString(columnIndex);
				cursor.close();
				addFragment(4);
			}
			break;

		case Constant.FACEBOOK_REQUEST:

			prefrences.setPostAvail(prefrences.getPostAvail() + 1);
			txtAvailablePost.setText(" " + prefrences.getPostAvail());
			break;

		default:
			break;
		}

	}

	// Custom Camera for WorkTive

	private Camera mCamera;
	private CameraPreview mPreview;
	RelativeLayout preview;

	boolean isCameraPreview;
	private Button mSnapButton, mSaveButton, mCancelButton;

	public void setCameraPreview() {
		Boolean hasCamera = checkCameraHardware(getApplicationContext());

		if (!hasCamera) {
			Toast.makeText(getApplicationContext(), "Camera Not Available",
					Toast.LENGTH_LONG).show();
		} else {
			// Create an instance of Camera
			mCamera = getCameraInstance();
			if (mCamera == null) {
				Toast.makeText(DrawerFragment.this,
						"Unable to open Camera \nPlease restart your device",
						Toast.LENGTH_SHORT).show();
				return;
			}
			// Create our Preview view and set it as the content of our
			// activity.
			mPreview = new CameraPreview(this, mCamera);
			preview = (RelativeLayout) findViewById(R.id.camera_preview);
			preview.setVisibility(View.VISIBLE);
			preview.addView(mPreview);

			mSaveButton = (Button) findViewById(R.id.button_Save);
			mCancelButton = (Button) findViewById(R.id.button_Cancel);
			mSnapButton = (Button) findViewById(R.id.button_capture);
			mSnapButton.bringToFront();
			mSaveButton.bringToFront();
			mCancelButton.bringToFront();
			mSnapButton.setText(R.string.take_photo);
			mSaveButton.setVisibility(View.GONE);
			mCancelButton.setVisibility(View.GONE);

			// capture image button
			mSnapButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// get an image from the camera
					if (mSnapButton.getText().toString()
							.equals(R.string.retake_photo)) {
						mCamera.startPreview();
					} else {
						mCamera.takePicture(null, null, mPicture);
					}

				}
			});
			mSaveButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					releaseCamera();
					addFragment(4);
					isCameraPreview = false;
					preview.setVisibility(View.GONE);
				}
			});

			mCancelButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					releaseCamera();
					isCameraPreview = false;
					preview.setVisibility(View.GONE);
				}
			});
		}

	}

	private Camera getCameraInstance() {
		Camera c = null;
		try {
			c = Camera.open(); // attempt to get a Camera instance
			isCameraPreview = true;
		} catch (Exception e) {
			// Camera is not available (in use or does not exist)
		}
		return c; // returns null if camera is unavailable
	}

	private PictureCallback mPicture = new PictureCallback() {

		@Override
		public void onPictureTaken(byte[] data, Camera camera) {

			File pictureFile = getOutputMediaFile(Constant.MEDIA_TYPE_IMAGE);
			if (pictureFile == null) {
				Log.d(TAG,
						"Error creating media file, check storage permissions");
				return;
			}

			try {
				FileOutputStream fos = new FileOutputStream(pictureFile);
				fos.write(data);
				fos.close();
				//
				// // BitmapFactory.Options bounds = new
				// BitmapFactory.Options();
				// // bounds.inJustDecodeBounds = true;
				// // Bitmap resizedBitmap = BitmapFactory.decodeFile(
				// // pictureFile.getAbsolutePath(), bounds);
				// // // BitmapFactory.decodeF
				// // Bitmap bm = BitmapFactory.decodeFile(
				// // pictureFile.getAbsolutePath(), bounds);
				// // ExifInterface exif = new ExifInterface(
				// // pictureFile.getAbsolutePath());
				// // String orientString = exif
				// // .getAttribute(ExifInterface.TAG_ORIENTATION);
				// // int orientation = orientString != null ? Integer
				// // .parseInt(orientString)
				// // : ExifInterface.ORIENTATION_NORMAL;
				// // int rotationAngle = 0;
				// // if (orientation == ExifInterface.ORIENTATION_ROTATE_90)
				// // rotationAngle = 90;
				// // if (orientation == ExifInterface.ORIENTATION_ROTATE_180)
				// // rotationAngle = 180;
				// // if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
				// // rotationAngle = 270;
				// //
				// // Matrix matrix = new Matrix();
				// // matrix.setRotate(rotationAngle,
				// // (float) bm.getWidth() / 2,
				// // (float) bm.getHeight() / 2);
				// // Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0,
				// // bounds.outWidth, bounds.outHeight, matrix, true);
			} catch (FileNotFoundException e) {
				Log.d(TAG, "File not found: " + e.getMessage());
			} catch (IOException e) {
				Log.d(TAG, "Error accessing file: " + e.getMessage());
			}
			mSaveButton.setVisibility(View.VISIBLE);
			mSnapButton.setText(R.string.retake_photo);
			mCancelButton.setVisibility(View.VISIBLE);
			// mSaveButton.invalidate();
			// mCancelButton.invalidate();
			picturePath = pictureFile.toString();
			// releaseCamera();
			// addFragment(4);
			// isCameraPreview = false;
			// preview.setVisibility(View.GONE);
		}
	};

	/** Create a File for saving an image */
	private static File getOutputMediaFile(int type) {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.

		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				"WorkTive");
		// This location works best if you want the created images to be shared
		// between applications and persist after your app has been uninstalled.

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("WorkTive", "failed to create directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)
				.format(new Date());
		File mediaFile;
		if (type == Constant.MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
		} else {
			return null;
		}

		return mediaFile;
	}

	/** Check if this device has a camera */
	private boolean checkCameraHardware(Context context) {
		if (context.getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_CAMERA)) {
			// this device has a camera
			return true;
		} else {
			// no camera on this device
			return false;
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// release the camera
		if (mCamera != null) {
			mCamera.setPreviewCallback(null);
			mPreview.getHolder().removeCallback(mPreview);
			releaseCamera();
			RelativeLayout preview = (RelativeLayout) findViewById(R.id.camera_preview);
			preview.removeView(mPreview);
			mPreview = null;
		}
	}

	// Releasing the camera resources
	private void releaseCamera() {
		if (mCamera != null) {
			mCamera.release(); // release the camera for other applications
			mCamera = null;
		}
	}

	@SuppressLint("NewApi")
	@Override
	protected void onResume() {
		super.onResume();
		if (isCameraPreview) {
			Log.v(TAG, "Camera is Opened...");
			// Getting the camera resources back
			try {
				// open the default camera
				mCamera = Camera.open(0);
				// mCamera = getCameraInstance();
				mCamera.setPreviewCallback(null);
				mPreview = new CameraPreview(DrawerFragment.this, mCamera);// set
				// preview

				RelativeLayout preview = (RelativeLayout) findViewById(R.id.camera_preview);
				preview.addView(mPreview);
				mSnapButton = (Button) findViewById(R.id.button_capture);
				mSnapButton.bringToFront();
			} catch (Exception e) {
				Log.d(TAG, "Error starting camera preview: " + e.getMessage());
			}
		}
	}

	void startJsonParser4RCategory(JSONObject jsonObject) {
		new JsonParser4RCategory().execute(jsonObject);
	}

	class JsonParser4RCategory extends AsyncTask<JSONObject, Void, Void> {
		@Override
		protected Void doInBackground(JSONObject... params) {

			if (params[0] != null) {
				try {
					JSONObject jsonObject = new JSONObject(params[0].toString());
					JSONArray jsonArray = jsonObject
							.getJSONArray(Constant.RESPONSE);
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject jsonCategory = jsonArray.getJSONObject(i);
						com.sws.worktive.model.Category category = new com.sws.worktive.model.Category();
						category.setCategoryName(jsonCategory
								.optString(Constant.CATEGORY_NAME));
						category.setCategoryId(jsonCategory
								.optString(Constant.CATEGORY_ID));

						arrCategories.add(category);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (mProgressDialog != null && mProgressDialog.isShowing()) {
				mProgressDialog.dismiss();
			}
			if (arrCategories.size() != 0) {
				adapterJobTitle.notifyDataSetChanged();
			}
		}
	}

	@Override
	public void onDrawerClosed(View arg0) {
		//hide the keyboard whenever the fragment destroyed.
		InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	@Override
	public void onDrawerOpened(View arg0) {
		int id = arg0.getId();
		if (id == R.id.right_drawer_root) {
			ConnectionDector connectionDector = new ConnectionDector(
					this);
			if (connectionDector.isConnectingToInternet()) {
				if (arrCategories.size() == 0) {
					ServerDownload serverDownload = new ServerDownload(this, new ServerResponse() {
						
						@Override
						public void httpResponse(JSONObject jsonObject, String requestTag) {
							if (jsonObject != null) startJsonParser4RCategory(jsonObject);
						}
					},Constant.TAG_CATEGORY_REQUEST);
					
					List<NameValuePair> nameValuePairs = null;
					serverDownload.execute(nameValuePairs);
				}
			}
		}
		
	}

	@Override
	public void onDrawerSlide(View arg0, float arg1) {
		
	}

	@Override
	public void onDrawerStateChanged(int arg0) {
		
	}
	
	private void hideSignInField(){
		rl_signIn.setVisibility(View.GONE);
		findViewById(R.id.viewLineAboveSignIn).setVisibility(View.GONE);
	}
	
	private void hideSignOutField(){
		rl_signOut.setVisibility(View.GONE);
		findViewById(R.id.viewLineAboveSignOut).setVisibility(View.GONE);	
	}
	
	private void hideSignUpField(){
		rl_signUp.setVisibility(View.GONE);
		findViewById(R.id.viewLineAboveSignUp).setVisibility(View.GONE);
	}
	
	private void hideProfileField(){
		rl_Profile.setVisibility(View.GONE);
		findViewById(R.id.viewLineAboveProfile).setVisibility(View.GONE);
	}
	
	private void showSignInField(){
		rl_signIn.setVisibility(View.VISIBLE);
		findViewById(R.id.viewLineAboveSignIn).setVisibility(View.VISIBLE);
	}
	
	private void showSignOutField(){
		rl_signOut.setVisibility(View.VISIBLE);
		findViewById(R.id.viewLineAboveSignOut).setVisibility(View.VISIBLE);
	}
	
	private void showSignUpField(){
		rl_signUp.setVisibility(View.VISIBLE);
		findViewById(R.id.viewLineAboveSignUp).setVisibility(View.VISIBLE);
	}
	
	private void showProfileField(){
		rl_Profile.setVisibility(View.VISIBLE);
		findViewById(R.id.viewLineAboveProfile).setVisibility(View.VISIBLE);
	}
	
}
